package cn.yjr.vector;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.yjr.vector.tools.SharedPreferencesHelper;
import cn.yjr.vector.tools.StreamTool;
import cn.yjr.vector.tools.YJRHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * @author vector
 *
 */
public class CheckCaptchaActivity extends SherlockActivity implements OnClickListener{
	
	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Handler mHandler;
	Bitmap captcha_pic;
	String response, captcha;
	Context context;
	EditText register_input_phone_captcha_et;
	Button next_step_btn;
	boolean captcha_right = false;
	JSONObject jsonInfo;
	String new_phone, new_pwd;
	SharedPreferencesHelper spHelper;
	int category = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check_captcha);
		Intent intent = this.getIntent();
		new_phone = intent.getStringExtra("phone");
		new_pwd = intent.getStringExtra("new_pwd");
		inflater = this.getLayoutInflater();
		actionBar = getSupportActionBar();
		context = this;
		spHelper = new SharedPreferencesHelper(context);
		if(new_pwd==null||new_pwd.equals(""))
			category = 0;
		else{
			category = 1;
			getCaptcha();
		}
		initTitleBar();
		initView();
		initEventListener();
	
	}
	
	private void initTitleBar(){
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayUseLogoEnabled(false);
		ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
		title_bar = inflater.inflate(R.layout.register_action_bar2, null);
		actionBar.setCustomView(title_bar,lp);
	}
	private void initView(){
		register_input_phone_captcha_et  = (EditText) findViewById(R.id.register_input_phone_captcha);
		next_step_btn = (Button) findViewById(R.id.rg_next_btn_2);
		
	}
	private void initEventListener(){
		next_step_btn.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch( v.getId()){
		case R.id.rg_next_btn_2:
			captcha = register_input_phone_captcha_et.getText().toString();
			if(captcha==null||captcha.equals("")){
				Toast.makeText(context, "请输入手机验证码", Toast.LENGTH_SHORT).show();
			}else{
				checkCaptcha(captcha);
			}
			break;
		default:
			break;
		}
		
	}
	
	
	private void checkCaptcha(String captcha){
		//TODO
		final String captcha_ = captcha;
		RequestParams params = new RequestParams(); 
		params.add("verificationCode", captcha_);
		YJRHttpClient.post(context, "/user/checkVerificationCode.action", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							//Toast.makeText(context, "验证码验证成功", Toast.LENGTH_SHORT).show();
							if(category == 0)
								updatePhone();
							else if(category == 1)
								updatePwd(new_pwd);
						}else{
							YJRHttpClient.logCookie(context);
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	private void updatePhone(){
		YJRHttpClient.post(context, "/user/updateInfo.action", null, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							Toast.makeText(context, "更换手机号成功", Toast.LENGTH_SHORT).show();
							spHelper.putString("phone", new_phone);
							//TODO 更换完成后回到哪
							Intent intent = new Intent(CheckCaptchaActivity.this, AccountActivity.class);
							intent.putExtra("new_phone", new_phone);
							startActivity(intent);
							((Activity) context).finish();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
	
	/**
	 * @param md5
	 */
	private void updatePwd(String md5) {
		final String pwd_ = md5;
		RequestParams params = new RequestParams(); 
        params.add("password", pwd_);
		YJRHttpClient.post(context,"/user/updateInfo", params, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "修改密码成功", Toast.LENGTH_LONG).show();
							spHelper.putString("password", pwd_);
							Intent intent = new Intent(CheckCaptchaActivity.this, AccountActivity.class);
							intent.putExtra("new_pwd", new_pwd);
							startActivity(intent);
							((Activity) context).finish();
							//TODO 获取验证码
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
		
	}
	
	
	private void getCaptcha(){
		YJRHttpClient.post(context,"/user/changePassword", null, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							YJRHttpClient.setCookie(context); 
							Toast.makeText(context, "请填入手机验证码", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
	
}